package com.handong.handserialprogram.module.createmission.recordtask;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.handong.handserialprogram.R;
import com.handong.handserialprogram.model.PersonModel;
import com.handong.handserialprogram.model.entities.PersonEntity;
import com.handong.handserialprogram.module.base.SimpleFragment;
import com.handong.handserialprogram.utils.AsyncHttpUtil;
import com.handong.handserialprogram.utils.JLog;
import com.handong.handserialprogram.utils.SPUtil;
import com.handong.handserialprogram.utils.ViewUtil;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import org.apache.http.Header;

import java.util.ArrayList;

/**
 * CriminalFragment:犯人列表。
 */
public class CriminalFragment extends SimpleFragment {

    private static final String TAG = CriminalFragment.class.getSimpleName();
    private static final String IS_CRIMINAL = "isCriminal";
    public static final int TYPE_CRIMINAL = 1;
    public static final int TYPE_POLICE = 2;

    private LinearLayout mLoadingLayout;
    private RecyclerView mCriminalRV;
    private PersonAdapter mPersonAdapter;
    private FloatingActionButton mBackToTop;

    private ArrayList<PersonEntity> mCheckedList;
    private ArrayList<PersonEntity> mAllCriminalList;

    private String mTitle;
    private int mFragmentType = 0;

    public CriminalFragment() {
    }

    public static CriminalFragment newInstance(ArrayList<PersonEntity> list, boolean isCriminal) {
        CriminalFragment fragment = new CriminalFragment();
        fragment.mCheckedList = list;
        Bundle args = new Bundle();
        args.putBoolean(IS_CRIMINAL, isCriminal);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getContentViewID() {
        return R.layout.fragment_criminal;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            boolean isCriminal = getArguments().getBoolean(IS_CRIMINAL);
            if (isCriminal) {
                mFragmentType = TYPE_CRIMINAL;
            } else {
                mFragmentType = TYPE_POLICE;
            }
        }
    }

    @Override
    public void initViewByID(View contentView) {
        mLoadingLayout = (LinearLayout) contentView.findViewById(R.id.progressBarLayout);
        mCriminalRV = (RecyclerView) contentView.findViewById(R.id.criminalRecyclerView);
        //mBackToTop = (FloatingActionButton) contentView.findViewById(R.id.btnBackToTop);
        //mBackToTop.setOnClickListener(this);
        //contentView.findViewById(R.id.personSearchLayout).setOnClickListener(this);
        mTitle = getString(mFragmentType == TYPE_CRIMINAL ? R.string.title_choose_criminal_string
                : R.string.title_choose_police_string);
        initHeaderLayout(mTitle, getString(R.string.dialog_positive_text));
        requestCriminalList();

        //mCriminalRV.addOnScrollListener(new RecyclerView.OnScrollListener() {
        //  @Override
        //  public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        //      super.onScrollStateChanged(recyclerView, newState);
        //      JLog.d(TAG, "newState: " + newState);
        //       if (newState == RecyclerView.SCROLL_STATE_IDLE) {
        //           if (recyclerView.getChildLayoutPosition(recyclerView.getChildAt(0)) > 3) {
        //               mBackToTop.show();
        //           } else {
        //               mBackToTop.hide();
        //           }
        //      }
        //   }
        //});
    }

    @Override
    public void onClick(View v) {
        if (dispatchDoubleClick()){
            return;
        }
        switch (v.getId()) {
            case R.id.headerOptionLayout://保存
                showSaveDialog();
                break;
            case R.id.btnBackToTop:
                mCriminalRV.smoothScrollToPosition(0);
                mBackToTop.hide();
                break;
            case R.id.personSearchLayout:
                addFrag(SearchFragment.newInstance(mCheckedList, mFragmentType == TYPE_CRIMINAL), R.id.createMissionContainer
                        , R.anim.slide_y_middle_in, R.anim.anim_no);
                break;
            default:
                super.onClick(v);
        }
    }

    public void addCriminal(PersonEntity entity, boolean isRefresh) {
        if (isRefresh) {
            mAllCriminalList.add(0, entity);
            mPersonAdapter.notifyItemInserted(0);
            mCriminalRV.smoothScrollToPosition(0);
        }
        mCheckedList.add(entity);
        changeTitle(mTitle + "[已选:" + mCheckedList.size() + "]");
    }

    public void removeCriminal(PersonEntity entity) {
        mCheckedList.remove(entity);
        if (mCheckedList.isEmpty()) {
            changeTitle(mTitle);
        } else {
            changeTitle(mTitle + "[已选:" + mCheckedList.size() + "]");
        }
    }

    private void requestCriminalList() {
        RequestParams params = new RequestParams();
        if (TYPE_CRIMINAL == mFragmentType) {
            params.put("visit", "GetCriminals");
        } else {
            params.put("visit", "GetEmpleyee");
        }
        params.put("sys_companycode", SPUtil.getStringValue(SPUtil.LOGIN_CODE));
        AsyncHttpUtil.postSpecifiedRequest(getContext(), params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                getCriminalError("获取犯人列表失败");
            }

            @Override
            public void onRetry(int retryNo) {
                JLog.d(TAG, "onRetry:" + retryNo);
                super.onRetry(retryNo);
            }

            @Override
            public void onSuccess(int i, Header[] headers, String s) {
                JLog.d(TAG, s);
                if (TextUtils.isEmpty(s)) {
                    getCriminalError("获取列表为空");
                    return;
                }
                Gson gson = new Gson();
                PersonModel model = gson.fromJson(s, PersonModel.class);

                if (model.isSuccess()) {
                    getCriminalSuccess(model.getList());
                } else {
                    getCriminalError(model.getReason());
                }
            }
        });
    }

    private void getCriminalSuccess(ArrayList<PersonEntity> list) {
        //PersonEntity entity1 = null;
        //for (int i = 0; i < 30; i++) {
        //    entity1 = new PersonEntity();
        //    entity1.setId("00" + i);
        //    entity1.setName("强奸犯-朱林 " + i);
        //    list.add(entity1);
        //}
        if (list.isEmpty()) {
            getPersonListEmpty();
            return;
        }
        int flag = 0;
        int len = mCheckedList.size();
        mAllCriminalList = new ArrayList<>(len + list.size());
        if (len > 0) {
            mAllCriminalList.addAll(mCheckedList);
        }
        for (PersonEntity entity : list) {
            if (flag < len && mCheckedList.contains(entity)) {
                //entity.setChecked(true);
                flag++;
                continue;
            }
            mAllCriminalList.add(entity);
        }
        View childView = mLoadingLayout.getChildAt(0);
        if (childView instanceof ImageView) {
            dismissLoadingDialog();
        }
        FrameLayout parent = (FrameLayout) mLoadingLayout.getParent();
        parent.removeView(mLoadingLayout);
        mLoadingLayout = null;
        if (mCheckedList.isEmpty()) {
            changeTitle(mTitle);
        } else {
            changeTitle(mTitle + "[已选:" + mCheckedList.size() + "]");
        }
        mPersonAdapter = new PersonAdapter(this, mAllCriminalList, mFragmentType);
        mCriminalRV.setLayoutManager(new LinearLayoutManager(this.getContext()));
        mCriminalRV.setAdapter(mPersonAdapter);

        LinearLayout container = (LinearLayout) mCriminalRV.getParent();
        container.setVisibility(View.VISIBLE);
    }

    private void getPersonListEmpty() {
        FrameLayout parent = (FrameLayout) mLoadingLayout.getParent();
        parent.removeView(mLoadingLayout);

        if (mFragmentType == TYPE_CRIMINAL) {
            mLoadingLayout = super.showTipLayout(R.drawable.load_tip_empty, R.string.tip_no_criminal, null);
        } else {
            mLoadingLayout = super.showTipLayout(R.drawable.load_tip_empty, R.string.tip_no_police, null);
        }
        parent.addView(mLoadingLayout, 0);
    }

    private void getCriminalError(String reason) {
        View itemView = mLoadingLayout.getChildAt(0);
        if (itemView instanceof ImageView) {
            dismissLoadingDialog();
            return;
        }
        FrameLayout parent = (FrameLayout) mLoadingLayout.getParent();
        parent.removeView(mLoadingLayout);
        mLoadingLayout = super.showTipLayout(R.drawable.load_tip_error, R.string.tip_load_data_error, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showLoadDialog(getString(R.string.dialog_content_loading_person));
                requestCriminalList();
            }
        });
        parent.addView(mLoadingLayout, 0);
    }

    @Override
    protected boolean onBackClicked() {
        if (mPersonAdapter != null && !mCheckedList.isEmpty()) {
            showExitWarningDialog();
            return true;
        }
        return false;
    }

    @SuppressLint("StringFormatInvalid")
    private void showExitWarningDialog() {
        MaterialDialog dialog = new MaterialDialog.Builder(getContext())
                .title(R.string.dialog_title_careful)
                .content(getResources().getString(R.string.dialog_content_give_up_person, "人员"))
                .positiveColorRes(R.color.back_ground_green)
                .positiveText(R.string.dialog_positive_exit)
                .negativeColorRes(R.color.bg_gray)
                .negativeText(R.string.dialog_negative_text)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        mCheckedList.clear();
                        mActivity.savePersonList(mFragmentType);
                        removeFragment();
                    }
                })
                .build();
        ViewUtil.removeHomeKeyListener(dialog);
    }

    /**
     * 保存犯人
     */
    private void showSaveDialog() {
        mActivity.savePersonList(mFragmentType);
        removeFragment();
    }

    @Override
    public void onDestroyView() {
        if (mCriminalRV != null) {
            mCriminalRV.addOnScrollListener(null);
        }
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        if (mPersonAdapter != null) {
            mPersonAdapter.onDestroy();
            mPersonAdapter = null;
        }
        AsyncHttpUtil.cancelSpecifiedRequest(getContext());
        super.onDestroy();
    }
}
